/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2015-09-29 20:11:44
 * Last Modified: 2016-08-29 21:03:48
 * File Name: models/passport.go
 * Description:
 */
package models

import (
	"fmt"
	"time"

	"github.com/astaxie/beego"
	"github.com/garyburd/redigo/redis"
)

var (
	passportModel               *redis.Pool
	accessTokenExpireSecond     int
	acceptableURLTimestampDelta int
	captchaSendIntervalSecond   int64
	captchaTTL                  int64
	captchaSendLimitTimes       int
	avatarStoreDir              string
	avatarVisitUrlPrefix        string
)

func createRedisPool() {
	runmode := beego.AppConfig.DefaultString("runmode", "prod")
	ppserver := beego.AppConfig.DefaultString(fmt.Sprintf("redis_%s::ppserver", runmode), ":6380")
	ppMaxIdle := beego.AppConfig.DefaultInt(fmt.Sprintf("redis_%s::ppMaxIdle", runmode), 10)
	ppPassword := beego.AppConfig.DefaultString(fmt.Sprintf("redis_%s::ppPassword", runmode), "")
	passportModel = &redis.Pool{
		MaxIdle: ppMaxIdle,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", ppserver, redis.DialPassword(ppPassword))
			if err != nil {
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

/*
	URL时间验证的有效时间差范围值
*/
func GetAccesptableURLTimestampDelta() int64 {
	return int64(acceptableURLTimestampDelta)
}

/*
	获取redisPool对象
*/
func GetPassportModel() *redis.Pool {
	return passportModel
}

/*
	获取AccessToken的有效时间
*/
func GetAccessTokenExpireSecond() int {
	return accessTokenExpireSecond
}

/*
	验证码发送的最小间隔时间
*/
func GetCaptchaSendIntervalSecond() int64 {
	return captchaSendIntervalSecond
}

/*
	验证码的生命周期
*/
func GetCaptchaTTL() int64 {
	return captchaTTL
}

/*
	验证码生命周期内最大发送次数
*/
func GetCaptchaSendLimitTimes() int {
	return captchaSendLimitTimes
}

/*
	获取头像保存地址
*/
func GetAvatarStoreDir() string {
	return avatarStoreDir
}

/*
	获取头像访问的URL地址前缀
*/
func GetAvatarURLPrefix() string {
	return avatarVisitUrlPrefix
}

func init() {
	accessTokenExpireSecond = beego.AppConfig.DefaultInt("accessTokenExpireSecond", 86400*30)
	acceptableURLTimestampDelta = beego.AppConfig.DefaultInt("acceptableURLTimestampDelta", 600)
	captchaSendIntervalSecond = int64(beego.AppConfig.DefaultInt("captchaSendIntervalSecond", 60))
	captchaTTL = int64(beego.AppConfig.DefaultInt("captchaTTL", 1800))
	captchaSendLimitTimes = beego.AppConfig.DefaultInt("captchaSendLimitTimes", 10)
	avatarStoreDir = beego.AppConfig.DefaultString("avatarStoreDir", "../uploads")
	avatarVisitUrlPrefix = beego.AppConfig.DefaultString("avatarVisitUrlPrefix", "http://avatar.dl.qkier.com/")
	createRedisPool()
}
